package cn.thornbird.orgsync.repository;

import cn.thornbird.orgsync.entity.TaskDetail;
import cn.thornbird.orgsync.entity.status.ExecuteStatus;
import cn.thornbird.orgsync.model.statistic.DateStatisticItem;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;

import java.util.Date;
import java.util.List;

public interface TaskDetailRepository extends BaseRepository<TaskDetail>,
        JpaRepository<TaskDetail, String>, JpaSpecificationExecutor<TaskDetail> {

    Long countByTaskId(String taskId);

    @Query(nativeQuery = true, value = "select plan_time as date, count(1) as total from ( " +
            "select plan_time, task_id as total from task_details " +
            "where plan_time between :startDate and :endDate group by plan_time, task_id) t " +
            "group by plan_time order by plan_time asc")
    List<DateStatisticItem> countByTaskIdAndDateRange(Date startDate, Date endDate);

    @Query(nativeQuery = true, value = "select plan_time as date, count(1) as total from task_details " +
            "where plan_time between :startDate and :endDate " +
            "group by plan_time order by plan_time asc")
    List<DateStatisticItem> countByDateRange(Date startDate, Date endDate);

    @Query(nativeQuery = true, value = "select plan_time as date, count(1) as total from task_details " +
            "where execute_status = :status and plan_time between :startDate and :endDate " +
            "group by plan_time order by plan_time asc")
    List<DateStatisticItem> countByExecuteStatusAndDateRange(short status, Date startDate, Date endDate);

    List<TaskDetail> findByExecuteStatusOrderByCreatedAt(ExecuteStatus executeStatus);

    List<TaskDetail> findByTaskIdAndPlanTimeOrderBySequenceIndex(String taskId, Date planTime);

}
